//  this library.
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:hktk_app/dao/industry_dao.dart';
import 'package:hktk_app/dao/my_dao.dart';
import 'package:hktk_app/exception/dao_exception.dart';
import 'package:hktk_app/model/home/exam_key_model.dart';
import 'package:hktk_app/model/industry/exam_model.dart';
import 'package:hktk_app/model/industry/category_model.dart';
import 'package:hktk_app/pages/select/select_subject_page.dart';
import 'package:hktk_app/pages/select/select_type_page.dart';
import 'package:hktk_app/util/data_util.dart';
import 'package:hktk_app/util/font_util.dart';

import 'package:hktk_app/util/toast_util.dart';
import 'package:hktk_app/util/view_util.dart';
import 'package:hktk_app/widget/select/exam_label_widget.dart';

/// 显示考试子类型的页面
class SelectExamWidget extends StatefulWidget {
  /// 行业名称
  final String industryName;

  /// 行业id
  final String industryId;

  /// 搜索关键字
  final String searchKey;

  /// 是否跳转首页
  final int pageIndex;

  const SelectExamWidget({
    super.key,
    required this.industryId,
    required this.industryName,
    required this.searchKey,
    required this.pageIndex,
  });

  @override
  State createState() => _SelectExamWidgetState();
}

class _SelectExamWidgetState extends State<SelectExamWidget> {
  late BuildContext _context;

  /// 相关数据
  late List<ExamModel> _list;

  /// 加载异步数据方法
  late Future<Map<String, dynamic>> _futureInit;

  /// 行业id
  late String _id;

  /// 子页面标题
  get _examTitle => Row(
    children: [
      if (widget.industryName == "已购")
        SvgPicture.asset(
          "images/select/select_exam_purchased.svg",
          width: 24,
          height: 24,
        ),
      hiSpace(width: 12),
      Text(
        widget.industryName,
        style: FontUtil.fontBlack1(16, fontWeight: FontWeight.w500),
      )
    ],
  );

  @override
  void initState() {
    super.initState();
    _id = widget.industryId;
    _list = [];
    _futureInit = _initData();
  }

  @override
  void dispose() {
    super.dispose();
    ToastUtil.loadingBoxRemove();
  }

  @override
  Widget build(BuildContext context) {

    _context = context;
    if (_id != widget.industryId) {
      _id = widget.industryId;
      _list = [];
      _futureInit = _initData();
    }
    // 获取安全边距
    var bottom = ScreenUtil().bottomBarHeight;
    return Container(
      padding: EdgeInsets.fromLTRB(30, 28, 30, bottom + 28),
      decoration: const BoxDecoration(color: colorWhite1),
      child: FutureBuilder<Map<String, dynamic>>(
        future: _futureInit,
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            // 判断是否加载成功
            Map<String, dynamic> data = snapshot.data;
            if (!data["suc"]) {
              WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
                ToastUtil.show(context: context, msg: data["msg"]);
              });
            }
            return _examShow();
          } else {
            // 加载中
            return const Center(
              child: CircularProgressIndicator(),
            );
          }
        },
      ),
    );
  }

  /// 初始化数据方法
  Future<Map<String, dynamic>> _initData() async {
    Map<String, dynamic> map = {};
    try {
      if (widget.industryId == "yigo") {
        _list = await MyDao.myBuyExam();
      } else {
        _list = await IndustryDao.examByIndustryId(widget.industryId);
      }
      map["suc"] = true;
    } catch (e) {

      map = {"suc": false, "msg": "未知错误，请重试"};
      if (e is DaoException) {

        map["msg"] = e.msg;
      }
    }
    return map;
  }

  _examShow() {
    // return Container(
    //   width: 200,
    //   height: 1.sh-ScreenUtil().statusBarHeight-60-ScreenUtil().bottomBarHeight -(ScreenUtil().bottomBarHeight+56),
    //   child: SingleChildScrollView(child: Column(
    //   children: [
    //     _examTitle,
    //     hiSpace(height: 10),
    //
    //     _examItems()
    //   ],
    // ),),);
    return Column(
      children: [
        _examTitle,
        hiSpace(height: 10),
        Expanded(child: _examItems()),
        SizedBox(height: 50)
      ],
    );
  }

  /// label 显示
  _examItems() {
    if (_list.isNotEmpty) {
      return GridView.count(
        padding: EdgeInsets.only(top: 20),
        crossAxisCount: 2,
        childAspectRatio: 249 / 72,
        mainAxisSpacing: 20,
        crossAxisSpacing: 20,
        children: _searchItems(),
      );
      return MediaQuery.removePadding(
        removeTop: true,
        context: _context,
        child: GridView.count(
          padding: EdgeInsets.only(top: 20),
          crossAxisCount: 2,
          childAspectRatio: 249 / 72,
          mainAxisSpacing: 20,
          crossAxisSpacing: 20,
          children: [..._searchItems(),..._searchItems()],
        ),
      );
    } else {
      return showNoData();
    }
  }

  /// 搜索返回对应数据方法
  _searchItems() {
    List<Widget> widgets = [];
    for (ExamModel model in _list) {
      if (widget.searchKey != "") {
        if (model.name!.contains(widget.searchKey)) {
          widgets.add(_examItem(model));
        }
      } else {
        widgets.add(_examItem(model));
      }
    }
    return widgets;
  }

  /// 显示选择考试item
  Widget _examItem(ExamModel model) {
    return GestureDetector(
      onTap: () {
        _examItemOnTap(model);
      },
      child: ExamLabelWidget.exam(text: model.name!),
    );
  }

  /// 考试被点击方法
  void _examItemOnTap(ExamModel model) {
    // 显示加载框方法
    ToastUtil.loadingBoxShow(_context);
    // 加载数据
    IndustryDao.leafList(examId: model.id!).then((value) {
      ToastUtil.loadingBoxRemove();
      if (value == null || value.isEmpty) {
        ToastUtil.show(context: _context, msg: "暂无数据");
      } else {
        // 缓存相关数据
        _saveExamKey(model);

        // 跳转对应页面
        CategoryModel model2 = value[0];
        int attribute = model2.attribute!;
        int i = attribute & 1;
        dataUtilComm.dataModel.examId = model.id!;
        dataUtilComm.dataModel.industryId = model.industryId!;
        if (i == 1) {
          // 最后一级，跳转选择科目页面
          Navigator.pushNamed(_context, "/select-category",arguments: {
            "examId": model.id!,
            "subjectList": value,
            "buyCategorys": model.categorys,
            "pageIndex": widget.pageIndex,
            "pageName":"/tab"
          });

        } else {
          // 不是最后一级，跳转选择类型页面
          Navigator.pushNamed(_context, "/select-type",arguments: {
                "examId": model.id!,
                "subjectList": value,
                "buyCategorys": model.categorys,
                "pageIndex": widget.pageIndex,
          });
        }
      }
    }).catchError((e) {
      // 关闭加载框
      ToastUtil.loadingBoxRemove();
      String msg = "未知错误，请重试";
      if (e is DaoException) {
        msg = e.msg;
      }
      ToastUtil.show(context: _context, msg: msg);
    });
  }

  /// 缓存对应行业考试方法
  void _saveExamKey(ExamModel model) {
    String iId = widget.industryId;
    String iName = widget.industryName;
    if (iId == "yigo") {
      iId = model.industryId!;
      iName = model.industryName ?? "";
    }
    ExamKeyModel examKey = ExamKeyModel(
      examId: model.id ?? "",
      examName: model.name ?? "",
      industryId: iId,
      industryName: iName,
    );
    IndustryDao.saveExamKey(examKey);
  }
}
